<template>
  <div class="mform">
    <div class="back">
      <Back>
        <div class="form-btn">
          <el-button type="primary" @click="save()">保存</el-button>
        </div>
      </Back>
    </div>
    <div style="padding: 10px;">
      <el-tabs type="card" v-model="active_name">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="base">
          <div class="form-content">
            <div class="form-box" style="width: 60%;">
              <el-form ref="formRef" :model="form" :rules="rules" :label-position="'left'" label-width="auto">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入名称" clearable />
                </el-form-item>
                <el-form-item label="背景颜色" prop="bg_color">
                  <el-input v-model="form.bg_color" placeholder="请输入背景颜色, #fff" clearable />
                </el-form-item>
                <el-form-item label="文字颜色" prop="txt_color">
                  <el-input v-model="form.txt_color" placeholder="请输入导航颜色, #000" clearable />
                </el-form-item>
                <el-form-item label="激活颜色" prop="act_color">
                  <el-input v-model="form.act_color" placeholder="请输入激活颜色, #f00" clearable />
                </el-form-item>
                <el-form-item label="状态" prop="state">
                  <el-radio-group v-model="form.state">
                    <el-radio :value="1" border>启用</el-radio>
                    <el-radio :value="2" border>禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="首页专题" prop="is_home">
                  <el-radio-group v-model="form.is_home">
                    <el-radio :value="1" border>是</el-radio>
                    <el-radio :value="2" border>否</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="轮播图" prop="banner">
                  <el-button type="primary" @click="addBannerItem">添加</el-button>
                  <span style="margin-left: 10px; color: red;">*尺寸: 750*300</span>
                </el-form-item>
                <el-form-item label=" ">
                  <div class="banner">
                    <div class="bitem" v-for="(item, index) in form.banner" :key="index">
                      <el-upload class="avatar-uploader" :action="`${$api}/common/upload/pic`" :headers="{
            token: $pinia.state.value.store.token
          }" :show-file-list="false" :on-success="(res) => handleBannerImgSuccess(res, index)">
                        <img v-if="item.img" :src="$imgUrl + item.img" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                          <Plus />
                        </el-icon>
                      </el-upload>
                      <el-input v-model="item.link" placeholder="请输入跳转链接"
                        style="width: 300px;margin: 0 20px"></el-input>
                      <el-icon color="#f00" size="20" @click="closeItem(index)">
                        <CloseBold />
                      </el-icon>
                    </div>
                  </div>
                </el-form-item>

              </el-form>
            </div>
          </div>
        </el-tab-pane>
        <!-- 楼层管理 -->
        <el-tab-pane label="楼层管理" name="floor">
          <div class="floor-box">
            <div class="tb">
              <el-button type="warning" @click.stop="addFloor">添加楼层</el-button>
              <el-table :data="floor_data" resizable border show-overflow-tooltip max-height="100%"
                @row-click="floorRowClick">
                <el-table-column label="名称" prop="name" align="center" width="auto">
                  <template #default="scope">
                    <el-input placeholder="请输入" v-model="scope.row.name"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="状态" prop="state" align="center" width="120">
                  <template #default="scope">
                    <el-select v-model="scope.row.state">
                      <el-option :value="1" label="启用"></el-option>
                      <el-option :value="2" label="禁用"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="排序" prop="sort" align="center" width="100">
                  <template #default="scope">
                    <el-input type="number" placeholder="请输入规格" v-model="scope.row.sort"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" column-key="handle" width="90" align="center">
                  <template #default="scope">
                    <el-button type="danger" @click.stop="delGoods(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="" width="30" align="center">
                  <template #default="scope">
                    <div>
                      <el-icon v-if="curr_floor == scope.row.uuid" color="#f00" size="20"
                        style="position: relative;top:3px;left:-10px">
                        <CaretRight />
                      </el-icon>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="gr">
              <el-divider content-position="left">楼层商品集合</el-divider>
              <el-input v-model="floor_goods" placeholder="请输入商品ID,英文逗号隔开" clearable @change="setFloorGoods"
                :autosize="{ minRows: 8, maxRows: 12 }" type="textarea" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script setup name="MallSpecialEdit">
const { proxy } = getCurrentInstance()

const formRef = ref();
const form = reactive({ id: '', name: '', bg_color: '', state: 1, banner: [], is_home: 2, txt_color: '', act_color: '',floor: [] });
//验证规则
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  state: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  is_home: [{ required: true, message: '请选择是否是首页专题', trigger: 'blur' }]
};

const active_name = ref('base')

const fuuid = uuid();
const floor_data = ref([
  {
    uuid: fuuid,
    name: '',
    sort: '',
    state: 1,
    goods_ids: ''
  }
])
const floor_goods = ref('')
//保存
async function save() {
  let is_empty = false
  floor_data.value.forEach(item=> {
    if(!item.name) {
      is_empty = true
    }
  })
  if(is_empty) {
    return ElMessage({ type: 'error', message: '商品楼层名称不能为空' });
  }
  form.floor = floor_data.value
  console.log(form)
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await proxy.$post('MallSpecialSave', form)
      if (res.code === 0) {
        ElMessage({ type: 'success', message: '保存成功' });
        proxy.$bus.emit('back');
      }
    }
  });
}

onMounted(() => {
  // 编辑
  let id = proxy.$route.query.id || null;
  if (id) {
    getDetail(id)
  }
});

async function getDetail(id) {
  let res = await proxy.$get('MallSpecialDetail', {
    id
  }, false)
  if (res.code === 0) {
    Object.assign(form, res.data);
    floor_data.value = res.data.floor || []
    floor_data.value.forEach((item,index)=> {
      item.uuid = item.id
      if(index == 0) {
        floor_goods.value = item.goods_ids
        curr_floor.value = item.id
      }
    })
  }
}

// 轮播图
function closeItem(index) {
  form.banner.splice(index, 1)
}
function addBannerItem() {
  form.banner.push({
    img: '',
    link: ''
  })
}
function handleBannerImgSuccess(res, index) {
  if (res.code == 0) {
    form.banner[index].img = res.data.url
  } else {
    ElMessage({ type: 'error', message: '上传失败' });
  }

}


function uuid() {
	var s = []
	var hexDigits = "0123456789abcdefg!@#$&*_STUVWXYZ"
	let tmp = new Date().getTime()
	for (var i = 0; i < 24; i++) {
		let index = Math.floor(Math.random() * 0x20)
		s[i] = hexDigits.substring(index, index + 1)
	}
	s[14] = "4" // bits 12-15 of the time_hi_and_version field to 0010
	s[8] = s[13] = s[18] = "-"
	var uuid = s.join("")
	uuid = tmp + "-" + uuid
	return uuid
}

function addFloor() {
  floor_data.value.push({
    uuid: uuid(),
    name: '',
    sort: '',
    state: 1,
    goods_ids: ''
  })
}
function delGoods(index) {
  floor_data.value.splice(index, 1)
  if(curr_floor.value == floor_data.value[index].uuid) {
    if(floor_data.value.length>0) {
      curr_floor.value = floor_data.value[0].uuid
      floor_goods.value = floor_data.value[0].goods_ids
    }
  }
  
}

const curr_floor = ref(fuuid)
function floorRowClick(row) {
  curr_floor.value = row.uuid
  floor_goods.value = row.goods_ids
}

// 设置商品集合
function setFloorGoods() {
  floor_data.value.forEach(item=> {
    if(item.uuid === curr_floor.value) {
      item.goods_ids = floor_goods.value
    }
  })
}

</script>
<style scoped lang="scss">
.bitem {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .avatar-uploader,
  .el-icon.avatar-uploader-icon {
    width: 100px;
    height: 60px;
  }

  .avatar-uploader .avatar {
    width: 100px;
    height: 60px;
  }
}

.floor-box {
  display: flex;

  .tb {
    width: 500px;
  }

  .gr {
    flex: 1;
    margin-left: 20px;
  }
}
</style>
